package com.mall.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description:
 * @Author: JK
 * @Date: create in 2021/7/29 17:48
 */
@Slf4j
@Component
public class PromoOrderConsumer {

    DefaultMQPushConsumer consumer;

    @Reference
    OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("promo_order_consumer");

        consumer.setNamesrvAddr("127.0.0.1:9876");

        try {
            consumer.subscribe("create_promotion_order", "*");
            consumer.setMessageListener(new MessageListenerConcurrently() {
                @Override
                public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                    MessageExt message = msgs.get(0);
                    byte[] body = message.getBody();
                    String s = new String(body, 0, body.length, StandardCharsets.UTF_8);

                    CreateSeckillOrderRequest createSeckillOrderRequest = JSON.parseObject(s, CreateSeckillOrderRequest.class);
                    System.out.println("createSeckillOrderRequest = " + createSeckillOrderRequest);
                    CreateSeckillOrderResponse createSeckillOrderResponse = orderPromoService.createPromoOrder(createSeckillOrderRequest);

                    // 根据response的结果，判断有没有消费成功
                    if (OrderRetCode.SUCCESS.getCode().equals(createSeckillOrderResponse.getCode())) {
                        log.info("PromoOrderConsumer 消费消息成功！");
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }
                    log.info("PromoOrderConsumer 消费消息失败！");
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;

                }
            });

            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

}
